package com.base.vistter.iframe.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.base.vistter.iframe.entity.SysDict;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.mapper.SysDictMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;

@Service
@Transactional
@Slf4j
public class SysDictService extends BaseService<SysDictMapper, SysDict> {

    @Resource(name = "sysDictItemService")
    private SysDictItemService sysDictItemService;

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean save(SysDict entity) throws IframeException {
        LambdaQueryWrapper<SysDict> lambdaQueryWrapper = new LambdaQueryWrapper<SysDict>();
        lambdaQueryWrapper.eq(SysDict::getCode , entity.getCode());
        SysDict sysDict = super.selectOne(lambdaQueryWrapper);
        if(sysDict != null){
            throw new IframeException("字典编码已存在");
        }
        return super.save(entity);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int delete(Serializable id) throws IframeException {
        sysDictItemService.deleteByDictIds(Arrays.asList(id));
        return super.delete(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int delete(Collection<?> idList) throws IframeException {
        sysDictItemService.deleteByDictIds(idList);
        return super.delete(idList);
    }
}
